const mongoose = require('mongoose')
const Statistics = mongoose.model('statistics')
const Setting = mongoose.model('setting')
const User = mongoose.model('user')
const Movie = mongoose.model('movie')

const { formatBody } = require('../../tools')

module.exports = {
  async append (ctx) {
    let ip = ctx.request.ip
    let { uid, type, page } = ctx.request.body
    let statistics = new Statistics({
      type,
      ip: ip || '',
      uid: uid || '',
      page: page || ''
    })
    await statistics.save()
    return ctx.body = formatBody(1, 'ok')
  },
  async allData (ctx) {
    let userTotal = await User.countDocuments()
    let movieTotal = await Movie.countDocuments()
    let PV = await Statistics.find({ type: 1 }).countDocuments()
    let UV = await Statistics.distinct('ip')
    let appDownNum = await Statistics.find({ type: 3 }).countDocuments()
    // let list = await Statistics.find({ type: 1 })
    return ctx.body = formatBody(1, 'ok', {
      userTotal,
      movieTotal,
      PV,
      UV: UV.length,
      appDownNum
    })
  },
  async list (ctx) {
    let page = ctx.query.page || 1
    let limit = ctx.query.limit || 20
    let type = ctx.query.type
    let uid = ctx.query.uid
    let query = {}
    if (type) query.type = type
    if (uid) query.uid = uid
    let list = await Statistics.find(query)
      .sort({ 'createdAt': -1 })
      .limit(+limit).skip(+limit * (+page - 1))
    let total = await Statistics.find(query).countDocuments()
    return ctx.body = formatBody(1, 'ok', { total, list })
  },
  async getAppDownLink (ctx) {
    let Arr = await Setting.find({})
    let ip = ctx.request.ip
    let statistics = new Statistics({
      type: 3,
      ip: ip || '',
      uid: '',
    })
    await statistics.save()
    return ctx.response.redirect(Arr[0].appDownLink)
  }
}